package com.example.movie.ui.video

import android.R
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.widget.FrameLayout
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import com.dueeeke.videoplayer.controller.ControlWrapper
import com.dueeeke.videoplayer.controller.IControlComponent
import com.dueeeke.videoplayer.exo.ExoMediaPlayerFactory
import com.dueeeke.videoplayer.player.AndroidMediaPlayerFactory
import com.example.movie.utils.Utils
import com.example.movie.utils.Utils.playState2str

/**
 * 调试信息
 */
open class DebugInfoView : AppCompatTextView, IControlComponent {
    private var mControlWrapper: ControlWrapper? = null

    constructor(context: Context?) : super(context!!) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(
        context!!, attrs
    ) {
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context!!, attrs, defStyleAttr
    ) {
    }

    override fun attach(controlWrapper: ControlWrapper) {
        mControlWrapper = controlWrapper
    }

    override fun getView(): View {
        return this
    }

    override fun onVisibilityChanged(isVisible: Boolean, anim: Animation) {}
    override fun onPlayStateChanged(playState: Int) {
        text = getDebugString(playState)
        bringToFront()
    }

    /**
     * Returns the debugging information string to be shown by the target [TextView].
     */
    private fun getDebugString(playState: Int): String {
        return """$currentPlayer${playState2str(playState)}
video width: ${mControlWrapper!!.videoSize[0]} , height: ${mControlWrapper!!.videoSize[1]}"""
    }

    private val currentPlayer: String
        get() {
            val player: String
            val playerFactory: Any = Utils.currentPlayerFactory
            player = when (playerFactory) {
                is ExoMediaPlayerFactory -> {
                    "ExoPlayer"
                }
                is AndroidMediaPlayerFactory -> {
                    "MediaPlayer"
                }
                else -> {
                    "unknown"
                }
            }
            return String.format("player: %s ", player)
        }

    override fun onPlayerStateChanged(playerState: Int) {
        bringToFront()
    }

    override fun setProgress(duration: Int, position: Int) {}
    override fun onLockStateChanged(isLocked: Boolean) {}

    init {
        setTextColor(ContextCompat.getColor(context, R.color.white))
        setBackgroundResource(R.color.black)
        textSize = 10f
        val lp = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        lp.gravity = Gravity.CENTER_HORIZONTAL
        layoutParams = lp
    }
}